package xyz.syyrjx.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.nio.charset.Charset;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/5 - 16:14
 */

@NoArgsConstructor
@AllArgsConstructor
@Data
public class SyyrjxRpcServer {

    private int port;

    public void run(ChannelInitializer<SocketChannel> channelInitializer) {
        NioEventLoopGroup bossGropup = new NioEventLoopGroup();
        NioEventLoopGroup workGropup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(bossGropup,workGropup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)//线程队列连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//保持连接
                    .childHandler(channelInitializer);
            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workGropup.shutdownGracefully();
            bossGropup.shutdownGracefully();
        }

    }


}
